package com.coursehub.course.config;

import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;
import java.util.ArrayList;

/**
 * JWT认证过滤器
 */
@Component
public class JwtAuthenticationFilter extends OncePerRequestFilter {
    
    private static final Logger log = LoggerFactory.getLogger(JwtAuthenticationFilter.class);

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
            throws ServletException, IOException {
        
        // 添加详细的请求信息调试
        System.out.println("[DEBUG] ===== JWT Filter Processing =====");
        System.out.println("[DEBUG] Request URI: " + request.getRequestURI());
        System.out.println("[DEBUG] Request Method: " + request.getMethod());
        
        // 打印所有请求头
        System.out.println("[DEBUG] All Headers:");
        java.util.Enumeration<String> headerNames = request.getHeaderNames();
        while (headerNames.hasMoreElements()) {
            String headerName = headerNames.nextElement();
            String headerValue = request.getHeader(headerName);
            System.out.println("[DEBUG]   " + headerName + ": " + headerValue);
        }
        
        log.debug("Processing request: {} {}", request.getMethod(), request.getRequestURI());
        
        String authHeader = request.getHeader("Authorization");
        log.debug("Authorization header: {}", authHeader != null ? "Bearer ***" : "null");
        
        // 从网关传递的用户信息
        String userId = request.getHeader("X-User-Id");
        String userAccount = request.getHeader("X-User-Account");
        String userName = request.getHeader("X-User-Name");
        
        System.out.println("[DEBUG] X-User-Id: " + userId);
        System.out.println("[DEBUG] X-User-Account: " + userAccount);
        System.out.println("[DEBUG] X-User-Name: " + userName);
        
        log.debug("X-User-Id: {}, X-User-Account: {}", userId, userAccount);
        
        // 如果有用户头信息，创建认证对象
        if (userId != null && userAccount != null) {
            // 创建用户认证对象
            UsernamePasswordAuthenticationToken authToken = 
                new UsernamePasswordAuthenticationToken(userAccount, null, new ArrayList<>());
            authToken.setDetails(userId); // 设置用户ID到details中
            
            // 设置到安全上下文
            SecurityContextHolder.getContext().setAuthentication(authToken);
            
            // 将认证信息设置到请求属性中，供RestTemplate拦截器使用
            request.setAttribute("X-User-Id", userId);
            request.setAttribute("X-User-Account", userAccount);
            if (userName != null) {
                request.setAttribute("X-User-Name", userName);
            }
            if (authHeader != null) {
                request.setAttribute("Authorization", authHeader);
            }
            
            log.debug("User authenticated: userId={}, userAccount={}", userId, userAccount);
            System.out.println("[DEBUG] User authenticated successfully");
        } else {
            log.warn("Missing user headers - X-User-Id: {}, X-User-Account: {}", userId, userAccount);
            System.out.println("[DEBUG] Missing user headers!");
        }
        
        System.out.println("[DEBUG] ===== JWT Filter End =====");
        filterChain.doFilter(request, response);
    }
}